﻿using System;
using System.IO;

namespace Ehai.Web.Framework.Rules
{
    class RecoverRuleHandle : IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员

#if DEBUG

        private int _execStatus = 0;
        public int ExecStatus
        {
            get { return _execStatus; }
        }
#endif

        public const string Name = "recover";


        #region 还原打包压缩的文件
        /// <summary>
        /// 还原打包压缩的文件
        /// </summary>
        /// <param name="p">
        /// 0： 处理类型——recover
        /// 1： 待还原文件(zip)文件路径(绝对路径地址)
        /// 2： 解压后的存放目录
        /// </param>
        /// <param name="ci">环境变量</param>
        /// <example>示例</example>
        /// <code>
        /// string[][] r=Execute(new string[3]{"recover","D:\\a.zip","E:\\recover\\a"},ci);
        /// </code>
        /// <exception cref="Ehai.Web.Framework.WebException">
        /// Ehai.Web.Framework.WebException:文件解压过程出现错误
        /// </exception>
        /// <returns>
        /// 返回值是一个二维交错数组，大小为[1][1]
        /// [0][0]中储存操作是否成功，返回值总是succeeded.如果出错只会抛出异常
        /// </returns>
        public string[][] Execute(string[] p, ContextInfo ci)
        {
            if (p.Length < 3)
            {

#if DEBUG
                _execStatus = -2;
#endif

                return null;
            }

            try
            {
                if (!File.Exists(p[1]))
                {

#if DEBUG
                    _execStatus = 1;
#endif

                    throw new Exception("指定的zip文件不存在：" + p[1]);
                }
                if (!Directory.Exists(p[2]))
                {

#if DEBUG
                    _execStatus = 2;
#endif

                    Directory.CreateDirectory(p[2]);
                }
                Zip.UnzipFiles(p[1], p[2], true);

                string[][] result = { new string[1] { "succeeded" } };

#if DEBUG
                _execStatus = 0;
#endif

                return result;
            }
            catch (Exception e)
            {

#if DEBUG
                _execStatus = -1;
#endif

                throw new Ehai.Web.Framework.WebException("Ehai.Web.Framework.Rules.Recover", "文件解压过程出现错误", e);
            }
        }
        #endregion
        public string GetHelpInfo()
        {
            return "还原打包压缩的文件";
        }

        public string GetHelpDetail()
        {
            return "还原打包压缩的文件.参数范例:{recover,D:/a.zip,E:/recover/a}";
        }

        public string[] GetParametersInfo()
        {
            string[] t = new string[3];
            t[0] = "[0]处理类型——recover";
            t[1] = "[1]待还原文件(zip)文件路径(绝对路径地址)";
            t[2] = "[2]解压后的存放目录";
            return t;
        }

        #endregion
    }
}
